package com.example.petstore.controller;

import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.User;
import com.example.petstore.domain.UserInfo;
import com.example.petstore.service.CodeService;
import com.example.petstore.service.UserInfoService;
import com.example.petstore.service.UserService;
import com.example.petstore.util.ALIYUNCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.StringTokenizer;

//@SessionAttributes({"loginUser", "giteeCustome", "giteeReason", "giteeId", "verifyCode"})
@Controller
@SessionAttributes({"loginAdmin"})
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private UserInfoService userInfoService;
    @PostMapping("/loginByName")/*test ok*/
//    public String loginByName(@RequestBody User user, String code){   //前端用json封装
//    public String loginByName(@ModelAttribute User user, String code, Model model){  //前端提交表单 x-www-form
    public String loginByName(String username, String password, String code, ModelMap model){
//        form-date ok;x-www-form ok;
//        ?xxx=xxx ok
//        json不行，username,password为null
//        判断验证码


        String verifyCode = (String) model.getAttribute("verifyCode");
        System.out.println(code);
        System.out.println(verifyCode);

        if(!verifyCode.equals(code)){
            model.addAttribute("errorMsg", "验证码错误！");
//            回到登录页面
            return "user/loginByName";
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
//        System.out.println(user);
        CommonResponse commonResponse = userService.findUserByUsernameAndPassword(user.getUsername(), user.getPassword());
//        System.out.println(user1);

        if(commonResponse.isSuccess()){
            model.addAttribute("loginUser", commonResponse.getData());
//            到首页
            return "catalog/main";
        }
//        System.out.println(code);
        model.addAttribute("errorMsg", commonResponse.getMessage());
//        到登录页面
        return "user/loginByName";
    }

    @PostMapping("/loginByGitee")    //for test
    public String loginByGitee(ModelMap model){
        model.addAttribute("giteeCustome", "user");
        model.addAttribute("giteeReason", "login");
        return "redirect:https://gitee.com/oauth/authorize?client_id=ba92f844c06bf93080ad7fc1b86468a002305bc1a859e753eaffdf0d712b9351&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2FbindPhoneNumber&response_type=code";
    }

    @PostMapping("/loginByPhone")/*test ok*/
    public String loginByPhone(String phoneNumber, String phoneCode, ModelMap model){
        CommonResponse commonResponse = userService.loginByPhone(phoneNumber, phoneCode);
        if(commonResponse.isSuccess()){
            model.addAttribute("loginUser", commonResponse.getData());
//            到首页
            return "catalog/main";
        }
        model.addAttribute("errorMsg", commonResponse.getMessage());
//        到登录页面
        return "user/loginByPhone";
    }

    @GetMapping("/sendPhoneCodeForUserLogin")/*test ok*/
    @ResponseBody
    public CommonResponse sendPhoneCodeForUserLogin(String phoneNumber){
        return codeService.sendPhoneCodeForUser(phoneNumber, "login");
    }

    @GetMapping("/sendPhoneCodeForUserRegister")/*test ok*/
    @ResponseBody
    public CommonResponse sendPhoneCodeForUserRegister(String phoneNumber){
        return codeService.sendPhoneCodeForUser(phoneNumber, "register");
    }

    @GetMapping("/sendPhoneCodeForUserResetPassword")/*test ok*/
    @ResponseBody
    public CommonResponse sendPhoneCodeForUserResetPassword(String phoneNumber){
        return codeService.sendPhoneCodeForUser(phoneNumber, "reset");
    }

    @GetMapping("/resetPasswordForm")
    public String resetPasswordForm(){
        return "user/resetPassword";
    }


    @PostMapping("/resetPassword")/*test ok*/
    public String resetPassword(String phoneNumber, String password, String phoneCode, ModelMap model){
        CommonResponse commonResponse = userService.resetPassword(phoneNumber, password, phoneCode);
        if(commonResponse.isSuccess()){
            model.addAttribute("msg", commonResponse.getMessage());
//            到登陆了页面
            return "user/loginByName";
        }
        model.addAttribute("errorMsg", commonResponse.getMessage());
//            到重置密码
        return "user/resetPassword";
    }

    @RequestMapping("/bindPhoneNumberAndUsername")
    public String bindPhoneNumber(String username, String phoneNumber, String phoneCode, ModelMap model){
//         userService.bindPhoneNumberAndUsername(username, phoneNumber, phoneCode);
//        判断验证码是否合法
        CommonResponse commonResponse = codeService.checkPhoneCodeForUserRegister(phoneNumber, phoneCode);
        if(commonResponse.isSuccess()){
//            验证码合法
            commonResponse = userService.findUserByPhoneNumber(phoneNumber);
            if(commonResponse.isSuccess()){
//                手机号已被绑定
//            todo:手机号绑定页面
                model.addAttribute("errorMsg", "手机号已被绑定");
                return "test_index";
            }

            commonResponse = userService.findUserByUsername(username);
            if(commonResponse.isSuccess()){
//            todo:手机号绑定页面
                model.addAttribute("errorMsg", "用户名已被使用");
                return "test_index";
            }
//            手机号未被绑定
            String giteeid = (String) model.getAttribute("giteeId");
//            创建用户
            CommonResponse commonResponse1 = userService.saveUserByPhoneNumberAndGitee(username, phoneNumber, giteeid);
            if(commonResponse1.isSuccess()) {
                model.addAttribute("loginUser", commonResponse.getData());
//                绑定成功
//                todo:选择到首页还是完善信息”页面
                return "test_index";
            }
//            绑定失败
//            todo:手机号绑定页面
            model.addAttribute("errorMsg", "绑定失败");
            return "test_index";
        }else{
//            todo:手机号绑定页面
            model.addAttribute("errorMsg", commonResponse.getMessage());
            return "test_index";
        }
    }

    @PostMapping("/registerByPhone")/*test ok*/
    public String registerByPhone(String username, String password, String phoneNumber, String phoneCode, ModelMap model){
//        判断用户名是否被用
        CommonResponse commonResponse = userService.findUserByUsername(username);
        if(commonResponse.isSuccess()){
            model.addAttribute("errorMsg", "用户名已被使用");
//            到注册页面
            return "user/registerBuyer";
        }
//        判断手机号是否被用
        commonResponse = userService.findUserByPhoneNumber(phoneNumber);
        if(commonResponse.isSuccess()){
            model.addAttribute("errorMsg", "手机号已被使用");
//            到注册页面
            return "user/registerBuyer";
        }
//        判断手机验证码是否正确
        commonResponse = codeService.checkPhoneCodeForUserRegister(phoneNumber, phoneCode);
        if(commonResponse.isSuccess()){
            commonResponse = userService.saveUserByPhone(username, password, phoneNumber);
            if(commonResponse.isSuccess()){
//                注册成功
                model.addAttribute("loginUser", commonResponse.getData());
                model.addAttribute("msg", "注册成功，自动登录");
//                到首页
                return "catalog/main";
            }else{
//                注册失败
                model.addAttribute("errorMsg", "注册失败");
//                到注册页面
                return "user/registerBuyer";
            }
        }else{
//            到注册页面
            model.addAttribute("errorMsg", commonResponse.getMessage());
            return "user/registerBuyer";
        }
    }

    @RequestMapping("/registerByGitee")/*test ok*/
    public String registerByGitee(ModelMap model){
        model.addAttribute("giteeCustome", "user");
        model.addAttribute("giteeReason", "register");
        return "redirect:https://gitee.com/oauth/authorize?client_id=ba92f844c06bf93080ad7fc1b86468a002305bc1a859e753eaffdf0d712b9351&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2FbindPhoneNumber&response_type=code";
    }

    @GetMapping("/findUserByPhoneNumber")/*test ok*/
    @ResponseBody
    public CommonResponse findUserByPhoneNumber(String phoneNumber){
        CommonResponse commonResponse = userService.findUserByPhoneNumber(phoneNumber);
        if(commonResponse.isSuccess()){
            return CommonResponse.creatForSuccessMessage("手机号已注册");
        }else{
            return CommonResponse.creatForError("手机号未注册");
        }
    }

    @GetMapping("/findUserByUsername")/*test ok*/
    @ResponseBody
    public CommonResponse findUserByUsername(String username){
        CommonResponse commonResponse = userService.findUserByUsername(username);
        if(commonResponse.isSuccess()){
            return CommonResponse.creatForSuccessMessage("用户名已存在");
        }else{
            return CommonResponse.creatForError("用户名不存在");
        }
//        return userService.findUserByUsername(username);
    }

    @GetMapping("/changeInfo")/*test ok*/
    public String changeInfo(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        CommonResponse commonResponse = userInfoService.getUserInfoByUsername(user.getUsername());
        if(commonResponse.isSuccess()){
            model.addAttribute("userInfo", commonResponse.getData());
            System.out.println(commonResponse.getData());
//            todo：到用户信息修改页面
            return "test_index";
        }else{
            model.addAttribute("errorMsg", "出错了，请稍后再试");
//            到首页
            return "catalog/main";
        }
    }

    @PostMapping("/changeInfo")
    @ResponseBody
    public CommonResponse postChangeInfo(@ModelAttribute UserInfo userInfo, ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        CommonResponse commonResponse = userInfoService.saveUserInfo(user.getUsername(), userInfo);
        return commonResponse;
    }

    @GetMapping("/loginByNameForm")/*ok*/
    public String loginByNameForm(){
        return "user/loginByName";
    }

    @GetMapping("/loginByPhoneForm")
    public String loginByPhoneForm(){
        return "user/loginByPhone";
    }
}
